package cn.com.mma.mobile.tracking.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import cn.com.mma.mobile.tracking.api.Global;

/**
 * 获得设备信息
 * 
 * @author lincoln
 * 
 */
public class DeviceInfoUtil {


	private final static String SHA1_ALGORITHM = "SHA-1";
	private final static String CHAR_SET = "iso-8859-1";

	/**
	 * 获得系统版本
	 * 
	 * @return
	 */
	public static String getOSVersion() {
		return Build.VERSION.RELEASE;
	}

	/**
	 * 设备的名字
	 * 
	 * @return
	 */
	public static String getDevice() {
		return Build.MODEL;
	}

	/**
	 * 获得手机的：宽＊density + x + 高＊density
	 * 
	 * @param context
	 * @return
	 */

	public static String getResolution(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics metrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(metrics);
		return metrics.widthPixels  + "x" + metrics.heightPixels;
	}

	/**
	 * 获得注册运营商的名字
	 * 
	 * @param context
	 * @return
	 */
	public static String getCarrier(Context context) {
		TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		return manager.getNetworkOperatorName();
	}

	/**
	 * 获得设备IMEI标识
	 * 
	 * @param context
	 * @return
	 */
	public static String getImei(Context context) {
		TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		return manager.getDeviceId();
	}

	/**
	 * 获得本地语言和国家
	 * 
	 * @return
	 */
	public static String getLocale() {
		Locale locale = Locale.getDefault();
		return locale.getLanguage() + "_" + locale.getCountry();
	}

	/**
	 * 获得当前应用的版本号
	 * 
	 * @param context
	 * @return
	 */
	public static String appVersion(Context context) {
		String result = "1.0";
		try {
			result = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
		}

		return result;
	}

	/**
	 * 获得设备的IP地址
	 * 
	 * @param context
	 * @return
	 */

	public static String getIP(Context context) {
		String ip = null;
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			NetworkInterface inf = interfaces.nextElement();
			for (Enumeration<InetAddress> enumAddress = inf.getInetAddresses(); enumAddress.hasMoreElements();) {
				InetAddress in = enumAddress.nextElement();
				if (!in.isLinkLocalAddress()) {
					return in.getHostAddress();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ip;
	}

	/**
	 * 获得设备device 、id 、display、product等信息
	 * 
	 * @return
	 */
	public static String getModel() {
		String device = Build.DEVICE;
		String id = Build.ID;
		String display = Build.DISPLAY;
		String product = Build.PRODUCT;
		String board = Build.BOARD;
		String brand = Build.BRAND;
		String model = Build.MODEL;
		return device + "," + id + "," + display + "," + product + "," + board + "," + brand + "," + model;
	}

	/**
	 * 判断是否是wifi连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isWifi(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		return cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ? true : false;
	}

	/**
	 * 判断当前网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		if (context != null) {
			ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity == null) {
				return false;
			} else {
				NetworkInfo[] info = connectivity.getAllNetworkInfo();
				if (info != null) {
					for (int i = 0; i < info.length; i++) {
						if (info[i].getState() == NetworkInfo.State.CONNECTED) {
							return true;
						}
					}
				}
			}
		} else {
		}
		return false;
	}

	/**
	 * 获取当前应用的名字
	 * 
	 * @param context
	 * @return
	 */
	public static String getAppName(Context context) {
		PackageManager manager = context.getPackageManager();
		ApplicationInfo info = null;
		try {
			info = manager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			String appName = info.loadLabel(manager).toString();
			return appName;
		} catch (NameNotFoundException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		}
		return "";
	}

	/**
	 * 获得应用的包名
	 * 
	 * @param context
	 * @return
	 */
	public static String getPackageName(Context context) {
		return context.getPackageName();
	}

	/**
	 * 获得网管硬件地址
	 * 
	 * @param context
	 * @return
	 */
	public static String getMacAddress(Context context) {
		String result = "";
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (wifiManager != null) {
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			if (wifiInfo != null) {
				result = wifiInfo.getMacAddress();
			}
		}
		// Log.i("MAC Address", "macAdd:" + result);
		return result;
	}

	/**
	 * 获得设备ONIN,这里使用AndroidID
	 * 
	 * @param context
	 * @return
	 */
	public static String getODIN1(Context context) {
		String androidId;
		androidId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
		return SHA1(androidId);
	}

	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

	/**
	 * 对字符串进行加密处理
	 * 
	 * @param text
	 * @return
	 */
	private static String SHA1(String text) {
		try {
			MessageDigest md;
			md = MessageDigest.getInstance(SHA1_ALGORITHM);
			byte[] sha1hash;
			md.update(text.getBytes(CHAR_SET), 0, text.length());
			sha1hash = md.digest();
			return convertToHex(sha1hash);
		} catch (Exception e) {
			Logger.e("ODIN Error generating generating SHA-1: " + e);
			return null;
		}
	}

	/**
	 * 填充设备信息
	 * 
	 * @param context
	 */
	public static Map<String, String> fulfillTrackingInfo(Context context) {
		Map<String, String> params = new HashMap<String, String>();

		params.put(Global.TRACKING_LOCATION, LocationUtil.getInstance(context).getLocation());
		String mac = DeviceInfoUtil.getMacAddress(context);
		if (mac != null) {
			mac = mac.replaceAll(":", "").toUpperCase();
			params.put(Global.TRACKING_MAC, mac);

		}
		params.put(Global.TRACKING_ANDROIDID, getAndroidId(context));

		params.put(Global.TRACKING_OS_VERION, getOSVersion());
		params.put(Global.TRACKING_TERM, getDevice());
		params.put(Global.TRACKING_WIFI, isWifi(context) ? "1" : "0");
		params.put(Global.TRACKING_NAME, getAppName(context));
		params.put(Global.TRACKING_KEY, getPackageName(context));

		params.put(Global.TRACKING_OS_VERION, getOSVersion());
		params.put(Global.TRACKING_OS, "0");
		params.put(Global.TRACKING_SCWH, getResolution(context));
		params.put(Global.TRACKING_IMEI, getImei(context));
		params.put(Global.TRACKING_SDKVS, Global.TRACKING_SDKVS_VALUE);
		

		return params;
	}

	

	/**
	 * 初次获取设备唯一标识,经过md5处理
	 * 
	 * 9774d56d682e549c是模拟器的唯一标识，排除
	 * 
	 * @param mContext
	 */
	private static String generateAndroidId(Context mContext) {
		// Try to get the ANDROID_ID
		String android_id = Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID);
		if (android_id == null || android_id.equals("9774d56d682e549c") || android_id.length() < 15) {
			final SecureRandom random = new SecureRandom();
			android_id = new BigInteger(64, random).toString(16);
		}
		
		android_id = CommonUtil.md5(android_id);
		SharedPreferencedUtil.putString(mContext, SharedPreferencedUtil.SP_NAME_OTHER, SharedPreferencedUtil.SP_OTHER_KEY_ANDROID_ID, android_id);
		return android_id;
	}

	/**
	 * 从Sharedpreferenced中获取android_Id
	 * 
	 * @param mContext
	 * @return
	 */
	public static String getAndroidId(Context mContext) {
		String android_id = SharedPreferencedUtil.getString(mContext, SharedPreferencedUtil.SP_NAME_OTHER, SharedPreferencedUtil.SP_OTHER_KEY_ANDROID_ID);
		if (android_id == null || android_id.equals("") || android_id.equals("null")) {
			android_id = generateAndroidId(mContext);
		}
		return android_id;
	}

	/**
	 * 判断是否是模拟器
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isEmulator(Context context) {
		boolean result = false;
		String android_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
		if (android_id != null && android_id.equals("9774d56d682e549c")) {
			result = true;
		}
		return result;
	}

}
